/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rest.jbpm.task;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.identity.Group;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.identity.spi.IdentitySession;
import org.jbpm.pvm.internal.task.TaskImpl;
import org.jbpm.pvm.internal.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author jump
 */
public class FindPersonalTasksUnwrapped implements Command<List<Task>> {
    
    private static final Logger log = LoggerFactory.getLogger(FindPersonalTasksUnwrapped.class);
    private final String userId;
    
    public FindPersonalTasksUnwrapped(String userId) {
        this.userId = userId;
    }
            
    @Override
    public List<Task> execute(Environment environment) throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        
        IdentitySession identity = environment.get(IdentitySession.class);
        List<String> groupIds = new ArrayList<String>();
        for(Group g: identity.findGroupsByUser(userId))
            groupIds.add(g.getId());
        
        try {

            session = sessionFactory.openSession();
            List<Task> tasks = session.createCriteria(TaskImpl.class, "task")
                    .add(
                        Restrictions.and(
                            Restrictions.eq("assignee",userId),
                            Restrictions.eq("state", Task.STATE_OPEN)))
                    .setFetchMode("execution", FetchMode.JOIN)
                    .setFetchMode("execution.variables", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
                    .setFirstResult(0).list();
            
            log.info("{} tasks found",tasks.size());            
            
            return CollectionUtil.checkList(tasks,Task.class);
            
        } finally {
            if(session != null) session.close();
        }
    }
    
}
